import httplib2
import urllib
import webbrowser
import json
import logging

IG_CLIENT_ID = '33bc4d091a5e448c9c6d86f0ffece8ab'
IG_CLIENT_SECRET = 'e87a1393ccc1480498154501bdb444e1'
IG_AUTH_URL = 'https://api.instagram.com/oauth/authorize'
IG_TOKEN_URL = 'https://api.instagram.com/oauth/access_token'
IG_REDIRECT_URI = 'http://localhost:8080/instagram/callback'
# IG_ACCESS_TOKEN = '406922.33bc4d0.c27024cb9719417d8ddd0ac54f1b2289'

SC_CLIENT_ID = 'd8b086cc6bb0c148422125da1c421977'
SC_CLIENT_SECRET = '639cc8d3fde5dbf6667a0960e36e515d'
SC_AUTH_URL = 'https://soundcloud.com/connect'
SC_TOKEN_URL = 'https://api.soundcloud.com/oauth2/token'
SC_REDIRECT_URI = 'http://localhost:8080/soundcloud/callback'
# SC_ACCESS_TOKEN = '1-16561-263114-1da98710c5d2195e5'

logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(message)s',
        datefmt='[%Y-%m-%d %H:%M:%S %z]',
    )

def build_url(base, params):
    
    return '%s?%s' % (base, urllib.urlencode(params))

def serialize(dict_or_list):
    
    return json.dumps(dict_or_list, ensure_ascii = True, indent = 4)


h = httplib2.Http()

# connect to IG

try:
    ig_access_token = IG_ACCESS_TOKEN
    
except:

    params = {
        'client_id': IG_CLIENT_ID,
        'redirect_uri': IG_REDIRECT_URI,
        'response_type': 'code'
    }
    
    url = build_url(IG_AUTH_URL, params)
    
    webbrowser.open(url)
    
    code = raw_input('Code: ').strip()
    
    params = {
        'client_id': IG_CLIENT_ID,
        'client_secret': IG_CLIENT_SECRET,
        'redirect_uri': IG_REDIRECT_URI,
        'grant_type': 'authorization_code',
        'code': code
    }
            
    data = urllib.urlencode(params)
    response, content = h.request(IG_TOKEN_URL, method='POST', body=data)
    ig_access_token = json.loads(content)['access_token']
    
logging.info('Instagram access_token: %s' % ig_access_token)
    
# connect to SC

try:
    sc_access_token = SC_ACCESS_TOKEN

except:

    params = {
        'client_id': SC_CLIENT_ID,
        'redirect_uri': SC_REDIRECT_URI,
        'response_type': 'code',
    }
    
    url = url = build_url(SC_AUTH_URL, params)
    
    webbrowser.open(url)
    
    code = raw_input('Code: ').strip()
    
    params = {
        'client_id': SC_CLIENT_ID,
        'client_secret': SC_CLIENT_SECRET,
        'redirect_uri': SC_REDIRECT_URI,
        'grant_type': 'authorization_code',
        'code': code
    }
            
    data = urllib.urlencode(params)
    response, content = h.request(SC_TOKEN_URL, method='POST', body=data)
    sc_access_token = json.loads(content)['access_token']
    
logging.info('Soundcloud access_token: %s' % sc_access_token)

# get the Instagram user

ig_params = { 'access_token': ig_access_token }

response, content = h.request(build_url('https://api.instagram.com/v1/users/self', ig_params))
ig_me = json.loads(content)

ig_username = ig_me['data']['username']
ig_full_name = ig_me['data']['full_name']

logging.info(ig_username)
logging.info(ig_full_name)

# Get the Soundcloud user

sc_params = { 'oauth_token': sc_access_token }

response, content = h.request(build_url('https://api.soundcloud.com/me.json', sc_params))
sc_me = json.loads(content)

sc_username = sc_me['username']
sc_full_name = sc_me['full_name']

logging.info(sc_username)
logging.info(sc_full_name)

# get all my pictures

ig_params = { 'access_token': ig_access_token }

response, content = h.request(build_url('https://api.instagram.com/v1/users/self/media/recent', ig_params))
ig_media = json.loads(content)

ig_media_url_list = [ image['images']['standard_resolution']['url'] for image in ig_media['data'] ]
logging.debug(ig_media_url_list)

# get all my tracks/sets

sc_params = { 'oauth_token': sc_access_token }

response, content = h.request(build_url('https://api.soundcloud.com/me/tracks.json', sc_params))
sc_tracks = json.loads(content)

response, content = h.request(build_url('https://api.soundcloud.com/me/playlists.json', sc_params))
sc_sets = json.loads(content)

# pick up a picture (the first!)

artwork_url = ig_media_url_list[0]
logging.info(artwork_url)

# pick up a track/set

track = sc_tracks[0]
logging.info(track['uri'])

set = sc_sets[0]
logging.info(set['uri'])

# attach the picture to the track/set

sc_params = {
    'oauth_token': sc_access_token,
}

track_params = {
    '': 'ciao ciao',
    }

response, content = h.request(build_url('%s.json' % track['uri'], sc_params), method='PUT', body=serialize(track_params))
logging.info(content)